package com.pengpai.pangucms.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pengpai.pangucms.VO.CategoryVO;
import com.pengpai.pangucms.entity.*;
import com.pengpai.pangucms.service.*;
import com.pengpai.pangucms.utils.PageDomain;
import com.pengpai.pangucms.utils.R;
import com.pengpai.pangucms.utils.TreeUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Controller
public class PreController {

    @Resource
    private IWebCategoryService webCategoryService;

    @Resource
    private IWebArticleService webArticleService;

    @Autowired
    private IWebConfigPropertyService webConfigPropertyService;

    @Autowired
    private IWebConfigService webConfigService;

    @Resource
    private TemplateEngine templateEngine;

    @Resource
    private ISysFileinfoService sysFileinfoService;

    @Value("${pangu.upload.root}")
    private String rootPath;

    @Value("${pengpai.page.limit}")
    private String pageLimit;

    @Value("${pengpai.domain}")
    private String domain;
    @GetMapping("/createHeader")
    @ResponseBody
    public R createHeader(){
        String headerPath = rootPath + "/inc/header.html";
        File oldFile = new File(headerPath);
        if(oldFile.exists()){
            if(oldFile.delete()){
                System.out.println("原页面已被删除！");
            }else {
                System.out.println("原页面删除失败！");
            }
        }
        List<WebCategory> list = webCategoryService.list();
        Collections.sort(list, new Comparator<WebCategory>() {
            @Override
            public int compare(WebCategory o1, WebCategory o2) {
                return o1.getSort() - o2.getSort();
            }
        });
        List<CategoryVO> webCategoryList = new ArrayList<>();
        for (WebCategory wc : list) {
            if(wc.getIsDel() == 1 || wc.getIsShow() == 0) continue;
            CategoryVO categoryVO = new CategoryVO();
            categoryVO.setId(wc.getCategoryId());
            categoryVO.setTitle(wc.getCategoryName());
            categoryVO.setParentId(wc.getParentId());
            categoryVO.setVisitUrl(wc.getVisitUrl());
            if(wc.getCategoryModel() == 1){
                if(wc.getVisitUrl() == null || "".equals(wc.getVisitUrl())){
                    categoryVO.setHref("javascript:;");
                }else {
                    categoryVO.setHref(wc.getVisitUrl());
                }
            }else if(wc.getCategoryModel() == 2){
                categoryVO.setHref("/category/" + wc.getCategoryId() +"/p/1");
            }
            webCategoryList.add(categoryVO);
        }
        List<CategoryVO> acList = TreeUtil.webCategoryVoToTree(webCategoryList, 0);
        Context context = new Context();
        context.setVariable("wcl", acList);
        PrintWriter printWriter = null;
        try {
            //把静态文件生成到服务器本地
            File file = new File(headerPath);
            printWriter = new PrintWriter(file);
            templateEngine.process("website/header_tmp", context, printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return R.fail("静态化页面制作失败！");
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
        return R.success("Header页面制作成功！");
    }

    @GetMapping("/category/{id}/p/{page}")
    public String categoryList(@PathVariable String id, @PathVariable String page, Model model, HttpServletResponse response) throws IOException {
        WebCategory category = webCategoryService.getById(id);
        if(category == null) {
            response.sendRedirect(domain + "/404.html");
            return null;
        }else {
            model.addAttribute("wc", category);
            PageDomain pageDomain = new PageDomain();
            pageDomain.setPage(Integer.valueOf(page));
            pageDomain.setLimit(Integer.valueOf(pageLimit));
            Page<WebArticle> articlePage = new Page<>(pageDomain.getPage(), pageDomain.getLimit());
            QueryWrapper<WebArticle> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(StrUtil.isNotBlank(id), "category_id", id).eq("is_del", 0)
                    .eq("is_show", 1).orderByAsc("sort").orderByDesc("publish_time");
            List<WebArticle> webArticles = webArticleService.page(articlePage,queryWrapper).getRecords();
            for (WebArticle wa : webArticles) {
                //            String href = "/" + category.getVisitUrl() + "/" + wa.getArticleId();
                String href = "/pages/"+ wa.getArticleId();
                wa.setHref(href);
                String imgUUid = wa.getCoverImage();
                if("".equals(imgUUid)) continue;
                QueryWrapper<SysFileinfo> query = new QueryWrapper<>();
                query.eq("file_code", imgUUid);
                SysFileinfo fileinfo = sysFileinfoService.getOne(query);
                wa.setCoverImage(imgUUid + fileinfo.getFileSuff());
            }
            model.addAttribute("was", webArticles);
            model.addAttribute("currentPage", articlePage.getCurrent());
            model.addAttribute("total", articlePage.getTotal());
            return "website/category_tmp";
        }
    }

    @GetMapping("/createFooter")
    @ResponseBody
    public R createFooter(WebConfigProperty webConfigProperty){
        String Path = rootPath + "/inc/footer.html";
        File oldFile = new File(Path);
        if(oldFile.exists()){
            if(oldFile.delete()){
                System.out.println("原页面已被删除！");
            }else {
                System.out.println("原页面删除失败！");
            }
        }

        WebConfigProperty property = webConfigPropertyService.getById(webConfigProperty.getId());

        QueryWrapper<WebConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("config_code","link").orderByAsc("order_id");
        List<WebConfig> webConfigs = webConfigService.getBaseMapper().selectList(queryWrapper);


        QueryWrapper<WebConfig> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("config_code","qrcode").orderByAsc("order_id");
        List<WebConfig> qrcode = webConfigService.getBaseMapper().selectList(queryWrapper1);


        Context context = new Context();
        context.setVariable("property", property);
        context.setVariable("list",webConfigs);
        context.setVariable("qrcode",qrcode);
        PrintWriter printWriter = null;
        try {
            //把静态文件生成到服务器本地
            File file = new File(Path);
            printWriter = new PrintWriter(file);
            templateEngine.process("website/footer_tmp", context, printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return R.fail("静态化页面制作失败！");
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
        return R.success("Header页面制作成功！");
    }

    @GetMapping("/createContact")
    @ResponseBody
    public R createContact(){
        String Path = rootPath + "/contact.html";
        File oldFile = new File(Path);
        if(oldFile.exists()){
            if(oldFile.delete()){
                System.out.println("原页面已被删除！");
            }else {
                System.out.println("原页面删除失败！");
            }
        }

        WebConfigProperty property = webConfigPropertyService.getById(1);


        Context context = new Context();
        context.setVariable("property", property);

        PrintWriter printWriter = null;
        try {
            //把静态文件生成到服务器本地
            File file = new File(Path);
            printWriter = new PrintWriter(file);
            templateEngine.process("website/contact_tmp", context, printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return R.fail("静态化页面制作失败！");
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
        return R.success("Contact页面制作成功！");
    }

    @GetMapping("/staticPage")
    @ResponseBody
    public R staticPage(String code){
        String path = rootPath+ "/"+code+".html";
        File oldFile = new File(path);
        if(oldFile.exists()){
            if(oldFile.delete()){
                System.out.println("原页面已删除");
            }else{
                System.out.println("原页面删除失败");
            }
        }
        QueryWrapper<WebConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("config_code",code).orderByAsc("order_id");
        List<WebConfig> list = webConfigService.getBaseMapper().selectList(queryWrapper);
        Context context = new Context();
        context.setVariable("list",list);
        PrintWriter printWriter = null;
        try {
            //把静态文件生成到服务器本地
            File file = new File(path);
            printWriter = new PrintWriter(file);
            templateEngine.process("website/"+code+"_tmp", context, printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return R.fail("静态化页面制作失败！");
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
        return R.success(code+"页面制作成功！");
    }
    @GetMapping("/createIndex")
    @ResponseBody
    public R createIndex(){
        String headerPath = rootPath + "/index.html";
        File oldFile = new File(headerPath);
        if(oldFile.exists()){
            if(oldFile.delete()){
                System.out.println("原页面已被删除！");
            }else {
                System.out.println("原页面删除失败！");
            }
        }
        // 配置
        QueryWrapper<WebConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("config_code","introduce").orderByAsc("order_id");
        List<WebConfig> introducions = webConfigService.getBaseMapper().selectList(queryWrapper);
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("config_code","advert").orderByAsc("order_id");
        List<WebConfig> adverts = webConfigService.getBaseMapper().selectList(queryWrapper);
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("config_code","service").orderByAsc("order_id");
        List<WebConfig> services = webConfigService.getBaseMapper().selectList(queryWrapper);
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("config_code","product").orderByAsc("order_id").last(" limit 4");
        List<WebConfig> products = webConfigService.getBaseMapper().selectList(queryWrapper);
        // 文章
        List<WebArticle> webArticles = webArticleService.selectThreeArticle();
        QueryWrapper<SysFileinfo> query = null;
        for (WebArticle wa : webArticles) {
            String imgUUid = wa.getCoverImage();
            query = new QueryWrapper<>();
            query.eq("file_code", imgUUid);
            SysFileinfo fileinfo = sysFileinfoService.getOne(query);
            wa.setCoverImage(imgUUid + fileinfo.getFileSuff());
        }
        QueryWrapper<WebArticle> articleQuery = new QueryWrapper<>();
        articleQuery.eq("is_cover", "1").eq("is_show", "1").orderByAsc("sort");
        List<WebArticle> coverArticle = webArticleService.getBaseMapper().selectList(articleQuery);
        for (WebArticle wa : coverArticle) {
            String imgUUid = wa.getCoverImage();
            query = new QueryWrapper<>();
            query.eq("file_code", imgUUid);
            SysFileinfo fileinfo = sysFileinfoService.getOne(query);
            wa.setCoverImage(imgUUid + fileinfo.getFileSuff());
        }

        Context context = new Context();
        context.setVariable("introducions", introducions);
        context.setVariable("adverts", adverts);
        context.setVariable("services", services);
        context.setVariable("products", products);
        context.setVariable("articles", webArticles);
        context.setVariable("coverArticle", coverArticle);
        PrintWriter printWriter = null;
        try {
            //把静态文件生成到服务器本地
            File file = new File(headerPath);
            printWriter = new PrintWriter(file);
            templateEngine.process("website/index_tmp", context, printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return R.fail("静态化页面制作失败！");
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
        return R.success("Header页面制作成功！");
    }
}
